import { observer, useLocalObservable } from 'mobx-react'
import styles from './index.module.less'
import Store from '../store'
import { CopyToClipboard } from 'react-copy-to-clipboard'
import robot_avatar from '@/resource/robot_avatar.png'
import BtnBotLayout from '@/components/BtnBotLayout'
import IconFont from '@/components/IconFont'
import { useEffect, useRef } from 'react'
import { Toast } from 'antd-mobile'
import { history } from 'umi'
import { SocketContainer } from '@/hooks/useSocket'
import { remove } from 'js-cookie'
import wx from 'weixin-webview-jssdk'

let timer: any
let i = 0
let outputText = ''
export default observer(() => {
    const store = useLocalObservable(() => Store)
    const { setEdit, answer, setAnswer, question, isOver, toggleIsOver, submitInfo } = store
    const textEl = useRef<any>()
    const textRef = useRef<any>('')
    const { send, onMessage, connect } = SocketContainer.useContainer()

    function typeWriter() {
        const text = textRef.current || ''
        outputText += text[i] || ''
        textEl.current.textContent = outputText
        i++
        if (i < text.length) {
            timer = setTimeout(typeWriter, 20)
        } else {
            clearTimeout(timer)
            timer = ''
        }
    }

    /** 停止生成 */
    const handleStop = () => {
        clearTimeout(timer)
        textEl.current.textContent = textRef.current
        send('close', { params: { session_code: submitInfo.session_code } })
    }

    /** 换个答案 */
    const handleChange = () => {
        if (submitInfo.used_num !== 20) {
            textEl.current.textContent = ''
            /** 初始化打字效果 */
            clearTimeout(timer)
            timer = null
            i = 0
            outputText = ''

            connect()
            send('submit', { params: { content: question } })
            toggleIsOver(false)
        } else {
            Toast.show('会话次数已用完')
        }
    }

    useEffect(() => {
        document.title = '自我介绍'
        /** 没有答案填写问题 */
        if (!question) {
            history.replace('/introduction')
            return
        }

        /** 接收答案 */
        function answerReceive({ data }: any) {
            if (textEl.current) {
                textRef.current = data?.content
                setAnswer(data?.content)
                if (!timer) {
                    typeWriter()
                }
            }
            document.getElementsByClassName(styles.wrapper)[0].scrollTop = document.getElementsByClassName(styles.wrapper)[0].scrollHeight
        }

        /** 接收答案 */
        function close() {
            toggleIsOver(true)
        }
        onMessage('answer', answerReceive)
        onMessage('close', close)

        return () => {
            remove('answer')
            remove('close', close)
            clearTimeout(timer)
        }
    }, [])

    return (
        <div className={styles.container}>
            <BtnBotLayout
                footer={
                    <div className={styles.options}>
                        <div
                            className={styles.edit_btn}
                            onClick={() => {
                                setEdit(true)
                                if (!isOver) {
                                    send('close', { params: { session_code: submitInfo.session_code } })
                                }
                                history.replace('/introduction')
                            }}
                        >
                            重新编辑
                        </div>
                        <div
                            className={styles.back_btn}
                            onClick={() => {
                                if (!isOver) {
                                    send('close', { params: { session_code: submitInfo.session_code } })
                                }
                                if (window.__wxjs_environment === 'miniprogram') {
                                    wx.miniProgram.navigateBack()
                                } else {
                                    history.goBack()
                                    // history.replace('/training')
                                }
                            }}
                        >
                            返回实训
                        </div>
                    </div>
                }
            >
                <div className={styles.wrapper}>
                    <img className={styles.robot_avatar} src={robot_avatar} />
                    <div className={styles.text_container}>
                        <span ref={textEl} />
                        &nbsp;
                        {!isOver && <span className={styles.cursor}>|</span>}
                    </div>
                    {!isOver && (
                        <div className={styles.action_wrapper}>
                            <span className={styles.action} onClick={handleStop}>
                                <IconFont type="icon-tingzhi" />
                                停止生成
                            </span>
                        </div>
                    )}
                    {isOver && (
                        <div className={styles.action_wrapper}>
                            <CopyToClipboard text={answer} onCopy={() => Toast.show('复制成功')}>
                                <span className={styles.action}>
                                    <IconFont type="icon-fuzhi" />
                                    <span>复制回答</span>
                                </span>
                            </CopyToClipboard>
                            <span className={styles.action} onClick={handleChange}>
                                <IconFont type="icon-shuaxin" />
                                换个回答
                            </span>
                            <span className={styles.count}>
                                <span className={styles.cur}>{submitInfo?.used_num || 1}</span>/20
                            </span>
                        </div>
                    )}
                </div>
            </BtnBotLayout>
        </div>
    )
})
